package org.netty.decoder;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * 固定长度的帧的解码
 * Description:
 * @author zpp
 * @date   2018年5月3日
 */
public class FixedLengthFrameDecoder extends ByteToMessageDecoder { //1

    private final int frameLength;
    
    /**
     * 
     * @param frameLength  指定产出的帧的长度
     */
    public FixedLengthFrameDecoder(int frameLength) { //2
        if (frameLength <= 0) {
            throw new IllegalArgumentException(
                    "frameLength must be a positive integer: " + frameLength);
        }
        this.frameLength = frameLength;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    	//检查是否有足够的字节用于读到下个帧
        if (in.readableBytes() >= frameLength) { //3
            ByteBuf buf = in.readBytes(frameLength);//4
            out.add(buf); //5
        }
    }
}